<template>
    <div class="pager-container" v-if="pageNumber > 1">
      <a @click="handClick(1)" :class="{disabled: current === 1}">首页</a>
      <a @click="handClick(current - 1)" :class="{disabled: current === 1}">上一页</a>
      <a @click="handClick(n)" 
      v-for="(n, i) in numbers" 
      :key="i" 
      :class="{active: n === current}"
      >{{n}}</a>
      <a @click="handClick(current + 1)" :class="{disabled: current === pageNumber}">下一页</a>
      <a @click="handClick(pageNumber)" :class="{disabled: current === pageNumber}">尾页</a>
    </div>
  </template>
  
  <script>
  export default {
    props: {
      current: {
        type: Number,
        required: false,
        default: 1,
      },
      total: {
        type: Number,
        required: false,
        default: 0,
      },
      limit: {
        type: Number,
        required: false,
        default: 10,
      },
      visibleNumber: {
        type: Number,
        required: false,
        default: 10,
      },
    },
    computed:{
      pageNumber(){
        return Math.ceil(this.total / this.limit);
      },
      numbers(){
        let nums=[];
        for(let i = this.visibleMin; i <= this.visibleMax; i++){
          nums.push(i);
        }
        return nums;
      },  
      visibleMin(){
        let min = this.current - Math.floor(this.visibleNumber / 2);
        return min < 1 ? 1 : min;
      },
      visibleMax(){
        let max = this.visibleMin + this.visibleNumber - 1;
        return max > this.pageNumber ? this.pageNumber : max;
      },
    },
    methods:{
      handClick(newPage){
        if (newPage < 1) {
          newPage = 1;
        }
        if (newPage > this.pageNumber) {
          newPage = this.pageNumber;
        }
        if (newPage === this.current) {
          return;
        }
        // 抛出一个事件
        this.$emit("pageChange", newPage);
      }
    }
  }
  </script>
  
  <style lang="less" scoped>
  @import "~@/styles/var.less";
    .pager-container {
      display: flex;
      justify-content: center;
      margin: 20px 0;
      a{
        color: @primary;
        margin: 0 6px;
        cursor: pointer;
        &.disabled{
          color: @lightWords;
          cursor: not-allowed;
        }
        &.active{
          color: @words;
          font-weight: bold;
          cursor: text;
        }
      }
    }
  </style>